package com.tanx.cqrs.command.handler;

import com.tanx.cqrs.command.Command;
import com.tanx.cqrs.command.TargetAggregateIdentifier;
import lombok.Data;

import java.lang.reflect.Field;

/**
 * 命令处理器源数据
 */
@Data
public class CommandMeta {
    private TargetAggregateIdentifier identifier;
    private Field field;
    private String fieldName;
    private Class targetClass;

    public CommandMeta(TargetAggregateIdentifier identifier, Field field, String fieldName, Class targetClass) {
        this.identifier = identifier;
        this.field = field;
        this.fieldName = fieldName;
        this.targetClass = targetClass;
    }

    public CommandMeta(Class targetClass) {
        this.targetClass = targetClass;
    }

    public Object getFieldValue(Command command) {
        if (field == null) {
            return null;
        }
        field.setAccessible(true);
        Object value;
        try {
            value = field.get(command);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return value;
    }
}
